/**   
* @Title: RoleController.java 
* @Package com.csis.security.controller 
* @Description: TODO
* @author dailey  
* @date 2012-9-28
* @version V1.0   
*/
package com.csis.security.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.csis.framework.util.ServiceLocator;
import com.csis.framework.util.jqgrid.JqGridModel;
import com.csis.framework.util.jqgrid.JqGridUtils;
import com.csis.security.domain.Role;
import com.csis.security.domain.RoleFormBean;
import com.csis.security.service.RoleService;
import com.csis.system.common.IStaticData;
import com.csis.system.common.WebUtil;
import com.csis.system.common.convert.Converter.ConvertArray;
import com.csis.system.domain.CustomerFormBean;
import com.csis.system.domain.User;
import com.csis.system.service.UserService;

/**
 * @author dailey
 *
 */

@Controller
@RequestMapping("/security/role")
public class RoleController {
	private Log log = LogFactory.getLog(getClass());
	@Resource
	private RoleService roleService;

	final String BASE_URL = "/system/manager/admin/role/";

//	@RequestMapping("/debug")
	public String cheap(Model model, HttpSession session, RoleFormBean formBean) {
		//debug
		User user = (User) session.getAttribute(IStaticData.SESSION_USER);
		cheap(session, user);
		return toMainPage(model, session, formBean);
	}

	@RequestMapping("/toMain")
	public String toMainPage(Model model, HttpSession session, RoleFormBean formBean) {
		User user = (User) session.getAttribute(IStaticData.SESSION_USER);

		Set<Role> roles = roleService.getRolesByUser(user);
		formBean.setTreeStr(roleService.generateRoleMenu(roles));
		if (!StringUtils.isBlank(formBean.getTreeStr()))
			formBean.setTreeStr(formBean.getTreeStr().replace("\n", ""));

		model.addAttribute("roleFormBean", formBean);
		return "main";
	}

	/**
	 * @param user
	 */
	protected User cheap(HttpSession session, User user) {
		//		if (user == null) {
		UserService userService = ServiceLocator.getInstance().getService("userService", UserService.class);
		user = userService.loadUser("admin");
		session.setAttribute(IStaticData.SESSION_USER, user);
		//		}
		return user;

	}

	@RequestMapping("/genRoleMenuXML")
	public void genRoleMenuXML(Model model, HttpSession session, HttpServletResponse response) throws Exception {
		response.setContentType("text/xml");
		response.setCharacterEncoding("UTF-8");
		PrintWriter os = null;

		try {
			os = response.getWriter();
			User user = (User) session.getAttribute(IStaticData.SESSION_USER);
			Set<Role> roles = roleService.getRolesByUser(user);
			os.print(roleService.generateRoleMenu(roles));
			os.flush();
		} catch (Exception e) {
			if (log.isErrorEnabled())
				log.error(e);
			else
				e.printStackTrace();
		} finally {
			if (os != null)
				os.close();
		}
	}

	@RequestMapping("/toAdd")
	public String add(Model model, HttpSession session) {
		RoleFormBean formBean = new RoleFormBean();
		Role bean = new Role();
		formBean.setBean(bean);
		model.addAttribute("formBean", formBean);
		return BASE_URL + "add";
	}

	@RequestMapping("/add")
	public @ResponseBody
	String add(RoleFormBean formBean) {
		String result = "0";
		Role bean = formBean.getBean();
		if (bean.getId() == null || bean.getRoleName() == null || "".equals(bean.getRoleName().trim())) {
			return result;
		}
		try {
			roleService.create(bean);
			result = "1";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/toEdit")
	public String edit(Model model, RoleFormBean formBean) {
		Integer id = formBean.getBean().getId();
		Role bean = roleService.load(id);
		formBean.setBean(bean);
		model.addAttribute("formBean", formBean);
		return BASE_URL + "modify";
	}

	@RequestMapping("/edit")
	public @ResponseBody
	String edit(RoleFormBean formBean) {
		String result = "0";
		Role bean = formBean.getBean();
		if (bean.getRoleName() == null || "".equals(bean.getRoleName().trim())) {
			return result;
		}
		try {
			roleService.update(bean);
			result = "1";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/list")
	public String list() {
		return BASE_URL + "listrole";
	}

	@RequestMapping("/listBy")
	public void listBy(JqGridModel model, HttpServletResponse response) {
		RoleFormBean formBean = WebUtil.buildConvert(model).convertToSingle(RoleFormBean.class);
		response.setContentType("text/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter os = null;
		try {
			roleService.list(formBean);
			os = response.getWriter();
			os.write(JqGridUtils.getJSONParser(RoleFormBean.class).parse(formBean).getContent());
			os.flush();
		} catch (IOException e) {
			if (log.isErrorEnabled())
				log.error(e);
			else
				e.printStackTrace();
		} catch (Exception e) {
			if (log.isErrorEnabled())
				log.error(e);
			else
				e.printStackTrace();
		} finally {
			if (os != null)
				os.close();
		}
	}

	@RequestMapping("/toDel")
	public @ResponseBody
	String remove(CustomerFormBean formBean) {
		String beanIds = formBean.getBeanIds();
		ConvertArray<Integer> ids = WebUtil.buildConvert(beanIds.split(",")).convertToArray(int.class);
		try {
			roleService.remove(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
		return "1";
	}

	@RequestMapping("/check")
	public @ResponseBody
	String checkExist(@RequestParam String exist) throws UnsupportedEncodingException {
		String roleName = "";
		if (exist != null) {
			roleName = URLDecoder.decode(exist, "UTF-8");
		}
		int size = roleService.getRolesByName(roleName).size();
		return size > 0 ? "1" : "0";
	}

}
